import {delay, toast} from "../../utils/tool";
import {APP_NAME} from "../../constant/index";

const app = getApp()
Page({
    data: {
        systemEmpty: false,
        systemList: [],
        systemStatus: 'loadMore',
        systemPage: 1,
        activeTab: 0,
        tabRect: [0, 0],
        tabList: [
            {
                label: '可领取',
                value: 0
            },
            {
                label: '我拥有',
                value: 1,
            }
        ],
        userList: [],
        userPage: 1,
        userStatus: 'loadMore',
        userEmpty: false,
        userInit: false,
    },

    changeTab(ev) {
        const {tab} = ev.currentTarget.dataset
        const value = tab * 1
        if (this.data.activeTab === value) return
        this.setData({
            activeTab: tab
        })
    },
    swiperChange(ev) {
        const {current} = ev.detail
        this.setData({
            activeTab: current
        })
        if (current === 1 && !this.data.userInit) return this.initData(true)
    },
    loadMoreData(ev) {
        const {type} = ev.currentTarget.dataset
        if (type === 'user') return this.initData(false)
        return this.initSystemCoupon(false)
    },
    initRect() {
        let selector = wx.createSelectorQuery().in(this)
        // selector.select('#tabConn').boundingClientRect()
        selector.selectAll('#tabConn .tab-item').boundingClientRect()
        selector.select('#tabConn .tab-slide').boundingClientRect()
        selector.exec(result => {
            const [items, slide] = result
            const {width: slideWidth} = slide
            const resp = items.map(item => {
                return item.left + (item.width / 2) - (slideWidth / 2)
            })
            this.setData({
                tabRect: resp,
            })
        })
    },
    onReady() {
        this.initRect()
    },
    getCoupon(ev) {
        const {id} = ev.currentTarget.dataset
        const target = this.data.systemList.find(item => item.id === id)
        if (!target) return;
        if (target.is_lingqu > 0) return toast({title: '您已经领取过了哦'})
        app.ajax({
            url: '/api/coupon/lingqucoupon',
            data: {coupon_id: id},
            success: resp => {
                const {code, msg} = resp
                toast({title: msg})
                if (code !== 1) return
                this.initSystemCoupon(true)
                this.data.userInit = false
            }
        })
    },

    initSystemCoupon(clear = false) {
        if (clear) {
            this.setData({
                systemEmpty: false,
                systemList: [],
                systemStatus: 'loading',
                systemPage: 1,
            })
        }
        if (this.data.systemStatus === 'noMore') return
        this.setData({
            systemStatus: 'loading'
        })
        const {systemPage} = this.data
        app.ajax({
            url: '/api/coupon/couponlist',
            data: {
                page: systemPage
            },
            success: ev => {
                const {code, data} = ev
                if (code !== 1) return this.setData({
                    systemEmpty: true,
                    systemStatus: 'noMore',
                })
                const {data: list, total, per_page, current_page} = data
                const hasMore = per_page * current_page < total
                let listData = []
                if (!!list && list.length) {
                    listData = list.map(item => {
                        return item
                    })
                }
                const {systemList} = this.data
                const listResult = [...systemList, ...listData]
                setTimeout(() => {
                    this.setData({
                        systemList: listResult,
                        systemStatus: hasMore ? 'loadMore' : 'noMore',
                        systemPage: hasMore ? systemPage + 1 : systemPage,
                        systemEmpty: listResult.length === 0
                    })
                }, 350)
            }
        })
    },
    formatDate(time) {
        const date = new Date(time * 1000)
        const [year, month, day] = [date.getFullYear(), date.getMonth() + 1, date.getDate()]
        return `${year}-${month < 10 ? '0' + month : month}-${day >= 10 ? day : '0' + day}`
    },
    toUseCoupon() {
        wx.switchTab({
            url: '/pages/index/index'
        })
    },
    initData(clear = false) {
        if (clear) {
            this.setData({
                userList: [],
                userPage: 1,
                userStatus: 'loading',
                userEmpty: false,
                userInit: false,
            })
        }
        const {userPage, userStatus} = this.data
        if (userStatus === 'noMore') return
        this.setData({
            userStatus: 'loading'
        })
        app.ajax({
            url: '/api/user/coupons',
            data: {page: userPage},
            success: async resp => {
                await delay(300)
                const {code, data, msg} = resp
                if (code !== 1) {
                    this.setData({
                        userStatus: 'noMore',
                        userEmpty: this.data.userList.length === 0,
                        userInit: false,
                    })
                    return toast({title: msg})
                }
                if (!data.data) data.data = []
                const {current_page, per_page, total, data: list} = data
                const hasMore = current_page * per_page < total
                const result = this.data.userList.concat(list.map(item => {
                    const createTime = this.formatDate(item['create_time'])
                    return {
                        ...item,
                        createTime,
                    }
                }))
                this.setData({
                    userInit: true,
                    userList: result,
                    userStatus: hasMore ? 'loadMore' : 'noMore',
                    userPage: hasMore ? userPage + 1 : userPage,
                    userEmpty: result.length === 0,
                })

            }
        })
    },
    onShareAppMessage() {
        return {
            title: APP_NAME,
            path: '/pages/get-coupon/get-coupon',
        }
    },
    onLoad: function () {
        this.initSystemCoupon()
        app.openShare()
    }
});
